import {XgPlayer} from "../index";
import {convertSeconds} from "../utils/time";

export class XgControlTime {
  root!: HTMLElement;
  constructor(private player: XgPlayer) {
    this.init();
    this.player.emitter.on('canplay', this.handleCanPlay.bind(this));
    this.player.emitter.on('timeupdate', this.handleTimeUpdate.bind(this));
  }
  private init() {
    this.root = document.createElement('div');
    this.root.className = 'time-wrap';
    this.root.innerHTML = `<span class="current">00:00</span>
                <span>/</span>
                <span class="duration">00:00</span>`;
  }
  private handleCanPlay() {
    const { duration } = this.player.videoInstance.videoEl;
    if (duration) {
      const durationSpan = this.root.getElementsByClassName('duration')[0];
      if (durationSpan) {
        const { minutes, seconds } = convertSeconds(duration);
        (durationSpan as HTMLElement).innerText = `${minutes}:${seconds}`;
      }
    }
  }
  private handleTimeUpdate(duration: number) {
    if (duration) {
      const currentSpan = this.root.getElementsByClassName('current')[0];
      if (currentSpan) {
        const { minutes, seconds } = convertSeconds(duration);
        (currentSpan as HTMLElement).innerText = `${minutes}:${seconds}`;
      }
    }
  }
}
